<?php

namespace app\admin\controller;

class Cate extends Base
{
    //栏目列表
    public function list()
    {
        //查询出栏目列表升序排序并分页
        $cates = model('Cate')->order('sort','asc')->paginate(3);
        //定义模板数据变量
        $viewData = [
            'cates' => $cates
        ];
        //渲染
        $this->assign($viewData);
        return view();
    }

    //栏目添加
    public function add()
    {
        //接收数据
        if (request()->isAjax()){
            $data = [
                'catename' => input('post.catename'),
                'sort' => input('post.sort')
            ];
            //将数据传递给模型并把结果返回给$result
            $result = model('Cate')->add($data);
            if ($result == 1){
                $this->success('栏目添加成功','admin/cate/list');
            }else{
                $this->error($result);
            }
        }
        return view();
    }

    //栏目排序
    public function sort()
    {
        //接收数据,只有一个，无需判断是否为Ajax
        $data = [
            'id' => input('post.id'),
            'sort' => input('post.sort')
        ];
        //将数据传递给模型并把结果返回给$result
        $result = model('Cate')->sort($data);
        if ($result == 1){
            $this->success('排序成功','admin/cate/list');
        }else{
            $this->error($result);
        }
    }

    //栏目编辑
    public function edit()
    {
        //接收数据
        if (request()->isAjax()){
            $data = [
                'id' => input('post.id'),
                'catename' => input('post.catename')
            ];
            //将数据传递给模型并把结果返回给$result
            $result = model('Cate')->edit($data);
            if ($result == 1){
                $this->success('栏目更新成功','admin/cate/list');
            }else{
                $this->error($result);
            }
        }

        //查询栏目id
        $cateInfo = model('Cate')->find(input('id'));
        //定义模板数据变量
        $viewData = [
            'cateInfo' => $cateInfo
        ];
        //渲染
        $this->assign($viewData);
        return view();
    }

    //栏目删除
    public function del()
    {
        //查询栏目id
        $cateInfo = model('Cate')->with('article,article.comments')->find(input('post.id'));
        foreach ($cateInfo['article'] as $k => $v){/*定位到栏目下的具体文章*/
            //删除栏目时，栏目下文章的评论也被删除
            $v->together('comments')->delete();
        }
        //将随文章一起的删除结果赋值给result
        $result = $cateInfo->together('article')->delete();
        if ($result){
            $this->success('栏目删除成功','admin/cate/list');
        }else{
            $this->error('栏目删除失败');
        }
    }
}
